package container

import (
	"context"
	"fmt"
	"gin_easy_starter/configs"
	mysql "gin_easy_starter/internal/repository"
	"gin_easy_starter/internal/router"
	"github.com/IBM/sarama"
	"github.com/go-redis/redis/v8"
)

func InitDB(server *router.Server) {
	dbRepo, _ := mysql.New()
	server.Db = dbRepo
}

func InitKafka(server *router.Server) {
	consumer, err := setupKafkaConsumer()
	if err != nil {
	}
	server.KafkaConsumer = consumer
}

func InitRedis(server *router.Server) {
	client := setUpRedisClient()
	server.RedisClient = client
}

func setupKafkaConsumer() (sarama.Consumer, error) {
	config := sarama.NewConfig()
	config.Consumer.Return.Errors = true

	// Specify your Kafka broker addresses
	brokerList := configs.Get().Kafka.BrokerList

	// Create a new consumer
	consumer, err := sarama.NewConsumer(brokerList, config)
	if err != nil {
		return nil, err
	}
	return consumer, nil
}

func setUpRedisClient() *redis.Client {
	// 配置Redis连接信息
	options := &redis.Options{
		Addr:     configs.Get().Redis.Addr, // Redis服务器地址
		Password: configs.Get().Redis.Pass, // Redis服务器密码，如果有的话
		DB:       configs.Get().Redis.Db,   // 使用的数据库索引，默认为0
	}

	// 创建Redis客户端
	client := redis.NewClient(options)

	// 使用Ping方法检查是否成功连接到Redis服务器
	pong, err := client.Ping(context.Background()).Result()
	if err != nil {
		fmt.Println("Failed to connect to Redis:", err)
		return nil
	}
	fmt.Println("Connected to Redis:", pong)
	return client
	// 在这里你可以使用client执行其他Redis命令
	// 例如：client.Set(context.Background(), "key", "value", 0)

	//// 关闭Redis客户端连接
	//err = client.Close()
	//if err != nil {
	//	fmt.Println("Error closing Redis client:", err)
	//}
}
